package com.example.redpacket.controller;


import com.example.redpacket.dto.RedPacketDto;
import com.example.redpacket.enums.StatusCode;
import com.example.redpacket.response.BaseResponse;
import com.example.redpacket.service.IRedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * @Description
 * @Author 大雄 <1194353393@qq.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/5/1 16:22
 */
@RestController
@RequestMapping("middleware/red/packet")
public class RedPacketController {

    private static final Logger log = LoggerFactory.getLogger(RedPacketController.class);

    private static final String prefix = "red/packet";

    @Autowired
    private IRedPacketService redPacketService;


    /**
     * 发红包
     */
    @PostMapping(value =  "/hand/out")
    public BaseResponse<String> handOut(@Validated @RequestBody RedPacketDto dto, BindingResult result) {
        if (result.hasErrors()) {
            return new BaseResponse<>(StatusCode.InvalidParams);
        }
        BaseResponse<String> response = new BaseResponse<>(StatusCode.Success);
        try {
            String redId = redPacketService.handOut(dto);
            response.setData(redId);

        } catch (Exception e) {
            log.error("发红包发生异常：dto={} ", dto, e.fillInStackTrace());
            response = new BaseResponse<>(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }


    /**
     * 抢红包
     */
    @GetMapping(value =   "/rob")
    public BaseResponse<BigDecimal> rob(@RequestParam Integer userId, @RequestParam String redId) {
        BaseResponse<BigDecimal> response = new BaseResponse<>(StatusCode.Success);
        try {
            BigDecimal result = redPacketService.rob(userId, redId);
            if (result != null) {
                response.setData(result);
            } else {
                response = new BaseResponse<>(StatusCode.Fail.getCode(), "红包已被抢完!");
            }
        } catch (Exception e) {
            log.error("抢红包发生异常：userId={} redId={}", userId, redId, e.fillInStackTrace());
            response = new BaseResponse<>(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }
}
























